﻿using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using SZORM.DbExpressions;
using SZORM.Factory;
using SZORM.Infrastructure;

namespace SZORM.Factory.PostgreSQL
{
    public class PostgreSQLDatabaseProvider : IDatabaseProvider
    {
        public string DatabaseType { get { return "PostgreSQL"; } }

        public DbConnection CreateConnection(string connStr)
        {
            return  new NpgsqlConnection(connStr);
        }
        public IDbExpressionTranslator CreateDbExpressionTranslator()
        {
            return DbExpressionTranslator.Instance;
        }
        public string CreateParameterName(string name)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            if (name[0] == UtilConstants.ParameterNamePlaceholer[0])
            {
                return name;
            }

            return UtilConstants.ParameterNamePlaceholer + name;
        }

        public IStructure CreateStructureCheck()
        {
            return new PostgreSQL.StructureToPostgreSQL();
        }

        public (int MinPoolSize, int MaxPoolSize) GetConnectionPoolNum(string connectionString)
        {
            var builder = new DbConnectionStringBuilder { ConnectionString = connectionString };

            int minPoolSize = 10;
            int maxPoolSize = 100;

            // 尝试各种可能的键名
            var minPoolKeys = new[] { "MinPoolSize" };
            var maxPoolKeys = new[] { "MaxPoolSize" };

            foreach (var key in minPoolKeys)
            {
                if (builder.TryGetValue(key, out var value))
                {
                    minPoolSize = Convert.ToInt32(value);
                    break;
                }
            }

            foreach (var key in maxPoolKeys)
            {
                if (builder.TryGetValue(key, out var value))
                {
                    maxPoolSize = Convert.ToInt32(value);
                    break;
                }
            }

            return (minPoolSize, maxPoolSize);
        }

        public DbExpressionVisitor<DbExpression> GetSqlGenerator()
        {
            return SqlGenerator.CreateInstance();
        }
    }
}
